package com.ziyia.viewmodel;

import android.app.PendingIntent;

import androidx.arch.core.util.Function;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MediatorLiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Transformations;
import androidx.lifecycle.ViewModel;

public class MainViewModel extends ViewModel {

    private final MutableLiveData<Integer> liveData = new MediatorLiveData<>();
    private MutableLiveData<User> userLiveData = new MediatorLiveData<>();

    private LiveData<String> userName = Transformations.map(userLiveData, new Function<User, String>() {
        @Override
        public String apply(User input) {
            return input.getName();
        }
    });

    private MutableLiveData<String> switchGetUserLiveData = new MediatorLiveData<>();

    private LiveData<User> switchUserLiveData = Transformations.switchMap(switchGetUserLiveData, new Function<String, LiveData<User>>() {
        @Override
        public LiveData<User> apply(String input) {
            return Repository.getUser(input);
        }
    });

    public void switchTest(String s) {
        switchGetUserLiveData.setValue(s);
    }

    public LiveData<User> getSwitchUserLiveData() {
        return switchUserLiveData;
    }

    public MainViewModel() {

    }

    public MainViewModel(Integer i) {
        liveData.setValue(i);
    }

    public final void plusOne() {
        Integer value = liveData.getValue();
        value = value == null ? 0 : value+1;
        liveData.setValue(value);

    }

    public final void clear() {
        liveData.setValue(0);
    }


    public MutableLiveData<Integer> getLiveData() {
        return liveData;
    }

    public User getUser() {
        return userLiveData.getValue();
    }


    public void setUser(User user) {
        userLiveData.setValue(user);
    }


    public LiveData<String> getUserName() {
        return userName;
    }

    @Override
    public String toString() {
        return "MainViewModel{" +
                "liveData=" + liveData +
                '}';
    }
}

